package org.beiji.frameworks.base;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * 解释一下为什么要实现ApplicationContextAware接口
 * 主要作用是让Spring的bean能够感知到Spring上下文
 * 当Spring检测到该类实现了ApplicationContextAware接口后，会自动调用setApplication
 */
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext CONTEXT;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.CONTEXT = applicationContext;
    }

    /**
     *
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T getBean(Class<T> clazz){
        return CONTEXT.getBean(clazz);
    }

    /**
     * 根据类名获取bean
     * @param name
     * @return
     */
    public static Object getBean(String name){
        return CONTEXT.getBean(name);
    }

    /**
     * 根据类名和类型获取bean
     * @param name
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T getBean(String name, Class<T> clazz){
        return CONTEXT.getBean(name, clazz);
    }

    /**
     * 获取改类型下的所有bean
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> clazz){
        return CONTEXT.getBeansOfType(clazz);
    }

    /**
     * 查找指定bean上的注解
     * @param name
     * @param annotationType
     * @return
     * @param <A>
     */
    public static <A extends Annotation> A findAnnotationOnBean(String name, Class<A> annotationType){
        return CONTEXT.findAnnotationOnBean(name, annotationType);
    }

    public static ApplicationContext getInstance(){
        return CONTEXT;
    }
}
